/* eslint-disable react-native/no-inline-styles */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
  FlatList,
  ScrollView,
  TouchableOpacity,
  View,
  Text,
  ActivityIndicator,
  StyleSheet
} from 'react-native';
import styled from 'styled-components';
import { Actions } from 'react-native-router-flux';
import { getMessDetail } from '../../api';
import { getToken } from '../../utils/auth';

let params = {
  prisonNo: '',
  topic: '',
  pageNum: 1,
  pageSize: 5,
  itemNumber: 0
};
let totalPage = 0;

class Detail extends Component {
  constructor() {
    super();
    this.state = {
      list: [],
      isLoading: true,
      //网络请求状态
      error: false,
      errorInfo: '',
      dataArray: [],
      showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      isRefreshing: false // 下拉控制
    };
  }
  fetchData(params, token, type) {
    //这个是js的访问网络的方法
    params.typeId = this.props.id;
    getMessDetail(params, token, type)
      .then(responseData => {
        if (responseData.code === '0') {
          if (type === 1) {
            this.setState({
              dataArray: []
            });
          }
          let data = responseData.data.rows;
          let dataBlob = [];
          let i = params.itemNumber;
          totalPage = Math.ceil(responseData.data.total / params.pageSize);
          data.map(function(item) {
            dataBlob.push({
              key: i,
              value: item
            });
            i++;
          });
          params.itemNumber = i;
          let foot = 0;
          if (params.pageNum >= totalPage) {
            foot = 1; //listView底部显示没有更多数据了
          }

          this.setState({
            //复制数据源
            dataArray: this.state.dataArray.concat(dataBlob),
            isLoading: false,
            showFoot: foot,
            isRefreshing: false
          });
          data = null;
          dataBlob = null;
        }
      })
      .catch(error => {
        this.setState({
          error: true,
          errorInfo: error
        });
      })
      .done();
  }
  componentDidMount() {
    //组件加载完成
    const { policeBaseInfoVo } = this.props;
    params = {
      prisonNo: '',
      topic: '',
      pageNum: 1,
      pageSize: 5,
      itemNumber: 0
    };

    params.prisonNo = policeBaseInfoVo.cusNumber;
    params.topic = policeBaseInfoVo.policeId;

    getToken().then(token => {
      this.fetchData(params, token);
    });
  }
  //加载等待页
  renderLoadingView() {
    return (
      <View style={styles.container}>
        <ActivityIndicator animating={true} color="#5593FF" size="large" />
      </View>
    );
  }
  //加载失败view
  renderErrorView() {
    return (
      <View style={styles.container}>
        <Text>加载失败</Text>
      </View>
    );
  }
  //返回itemView
  _renderItemView = ({ item }) => {
    // console.log(111111111, item);
    return (
      <Content>
        <UserBox>
          <Time>{item.value.mpiCreateDate}</Time>
          <OnTouchableOpacity>
            <UserPrefix>
              <TextContent>{item.value.mpiDesc}</TextContent>
              {item.value.mpiStatus === 0 ? <Point /> : <I />}
            </UserPrefix>
          </OnTouchableOpacity>
        </UserBox>
      </Content>
    );
  };

  _onRefresh = () => {
    this.setState({ refreshing: true });
    getToken().then(token => {
      this.fetchData(params, token, 1);
    });
  };

  renderData() {
    return (
      <FlatList
        data={this.state.dataArray}
        renderItem={this._renderItemView}
        ListFooterComponent={this._renderFooter.bind(this)}
        onEndReached={this._onEndReached.bind(this)}
        onEndReachedThreshold={1}
        refreshing={this.state.isRefreshing}
        onRefresh={this._onRefresh}
      />
    );
  }
  render() {
    //第一次加载等待的view
    if (this.state.isLoading && !this.state.error) {
      return this.renderLoadingView();
    } else if (this.state.error) {
      //请求失败view
      return this.renderErrorView();
    }
    //加载数据
    return (
      <Container>
        <Header>
          <HeaderTitle>{this.props.t_name}</HeaderTitle>
        </Header>
        {this.renderData()}
      </Container>
    );
  }
  _renderFooter() {
    if (this.state.showFoot === 1) {
      return (
        <View
          style={{
            height: 30,
            alignItems: 'center',
            justifyContent: 'flex-start'
          }}>
          <Text
            style={{
              color: '#999999',
              fontSize: 14,
              marginTop: 5,
              marginBottom: 5
            }}>
            没有更多数据了
          </Text>
        </View>
      );
    } else if (this.state.showFoot === 2) {
      return (
        <View style={styles.footer}>
          <ActivityIndicator />
          <Text>正在加载更多数据...</Text>
        </View>
      );
    } else if (this.state.showFoot === 0) {
      return (
        <View style={styles.footer}>
          <Text />
        </View>
      );
    }
  }
  _onEndReached() {
    //如果是正在加载中或没有更多数据了，则返回
    if (this.state.showFoot != 0) {
      return;
    }
    //如果当前页大于或等于总页数，那就是到最后一页了，返回
    if (params.pageNum != 1 && params.pageNum >= totalPage) {
      return;
    } else {
      params.pageNum++;
    }
    //底部显示正在加载更多数据
    this.setState({ showFoot: 2 });
    //获取数据
    getToken().then(token => {
      this.fetchData(params, token);
    });
  }
}

const mapStateToProps = ({ user: { policeBaseInfoVo } }) => {
  return {
    policeBaseInfoVo
  };
};

export default connect(mapStateToProps)(Detail);

const Container = styled.View`
  width: 100%;
  height: 100%;
  padding-left: 14;
  padding-right: 14;
  background-color: #f6f6f6;
`;

const Header = styled.View`
  padding-top: 8;
  padding-bottom: 8;
  width: 100%;
  background-color: white;
  border-bottom-width: 1;
  border-bottom-color: #ededed;
`;

const HeaderTitle = styled.Text`
  color: #070707;
  font-size: 16;
  text-align: center;
`;

const Content = styled.View`
  width: 100%;
  background-color: #f6f6f6;
`;
const UserBox = styled.View`
  margin-top: 15;
`;
const Time = styled.Text`
  text-align: center;
  color: black;
  font-size: 12;
  color: #333333;
`;
const UserPrefix = styled.View`
  padding-left: 10;
  padding-right: 10;
  padding-top: 15;
  padding-bottom: 15;
  border-radius: 4;
  margin-top: 5;
  background-color: white;
  flex-direction: row;
  align-items: center;
`;
const OnTouchableOpacity = styled.TouchableOpacity``;
const TextContent = styled.Text`
  font-size: 12;
  color: #333333;
`;
const Point = styled.Text`
  width: 6.67;
  height: 6.67;
  border-radius: 6.67;
  background-color: #ff634e;
  margin-left: 4;
`;
const I = styled.Text``;
const NoRecentContacts = styled.Text`
  padding-top: 20;
  text-align: center;
`;
const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF'
  },
  title: {
    fontSize: 15,
    color: 'blue'
  },
  footer: {
    flexDirection: 'row',
    height: 24,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 10
  },
  content: {
    fontSize: 15,
    color: 'black'
  }
});
